package org.iot.iotserver.netty.command;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.iot.iotserver.netty.config.NettyConstant;
import org.iot.iotserver.service.IIOTCommonService;

import java.util.Arrays;
import java.util.Optional;

/**
 * LED 控制 command
 */
public class LEDCommandExecutor implements IYCommandExecutor<String> {

    private static final Log log = LogFactory.get();

    private final IIOTCommonService iotCommonService;

    public LEDCommandExecutor(IIOTCommonService iotCommonService) {
        this.iotCommonService = iotCommonService;
    }

    @Override
    public boolean isMatching(String commandMetaData) {
        if(StrUtil.isEmpty(commandMetaData)) {
            return false;
        }
        String[] arr = commandMetaData.split("\\s+");
        if(arr.length < 3 || !"led".equalsIgnoreCase(arr[0])) {
            return false;
        }
        return true;
    }

    /**
     * 有效参数为最多 8 个, 第一个参数为身份 ID, 第二个参数为指定发送的设备, 后面的 1 ~ 8 个参数为编号 0 ~ 8 个开关的控制指令,
     * 1-开灯, 0-关灯, /-跳过该位置对应的开关指令。
     * @param args
     */
    @Override
    public String execute(ChannelHandlerContext context, String... args) {
        log.info("LEDCommandExecutor({})", Arrays.toString(args));

        if(!NettyConstant.LEGAL_MONITORS.contains(args[0])) {
            return "illegal client\r\n";
        }

        final String deviceName = args[1];
        String tStr = ArrayUtil.join(ArrayUtil.sub(args, 2, args.length), "");
        final String command = "led " + tStr;

        Optional<Channel> channelOpt = iotCommonService.findFirstChannel(channel -> {
            if(channel.hasAttr(NettyConstant.DEVICE_KEY)) {
                return deviceName.equalsIgnoreCase(String.valueOf(channel.attr(NettyConstant.DEVICE_KEY).get()));
            }
            return false;
        });

        if(channelOpt.isPresent()) {
            channelOpt.get().writeAndFlush(command + "\r\n");
            return "OK\r\n";
        }

        return "ERROR\r\n";
    }
}
